package com.huluobo.hyj.hyjmodel.adapter

import android.content.Context
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.huluobo.hyj.hyjmodel.widet.ReceiveMessageitemView
import com.huluobo.hyj.hyjmodel.widet.SendMessageitemView
import com.hyphenate.chat.EMMessage
import com.hyphenate.util.DateUtils

/**
 *@author : USER
 *@date : 2020/9/18 14:12
 *@params :
 *@description:
 */
class MessageListAdapter(val context:Context,val messages:List<EMMessage>) :
    RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    companion object{
        const val ITEM_TYPE_SEND_MESSAGE = 0
        const val ITEM_TYPE_PECEIVE_MESSAGE = 1
    }

    override fun getItemViewType(position: Int): Int {
        return if(messages[position].direct() == EMMessage.Direct.SEND){
            ITEM_TYPE_SEND_MESSAGE
        }else{
            ITEM_TYPE_PECEIVE_MESSAGE
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
       return if(viewType == ITEM_TYPE_SEND_MESSAGE){
           SendMessageViewHolder(SendMessageitemView(context))
       }else{
           ReceiveMessageViewHolder(ReceiveMessageitemView(context))
       }
    }
    override fun getItemCount(): Int =messages.size

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
       val showTimesTamp = isShowTimestamp(position)
        if(getItemViewType(position) == ITEM_TYPE_SEND_MESSAGE){
            val sendMessageItemView = holder.itemView as SendMessageitemView
            sendMessageItemView.bindView(messages[position],showTimesTamp)
        }else{
            val receiveMessageItemView = holder.itemView as ReceiveMessageitemView
            receiveMessageItemView.bindView(messages[position],showTimesTamp)
        }
    }

    private fun isShowTimestamp(position: Int): Boolean {
        //如果是第一条消息或者和前一条消息间隔时间比较长
        var showTimestamp = true
        if (position > 0) {
            showTimestamp =
                !DateUtils.isCloseEnough(messages[position].msgTime, messages[position - 1].msgTime)
        }
        return showTimestamp
    }

    class SendMessageViewHolder(itemView:View):RecyclerView.ViewHolder(itemView){

    }
    class ReceiveMessageViewHolder(itemView:View):RecyclerView.ViewHolder(itemView){

    }

}